package com.daltonsoft.daxc;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;

import com.daltonsoft.xmpp.XmppClient;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class LoginActivity extends Activity implements View.OnClickListener,
		Callable<XmppClient> {

	private Button loginButton;
	private EditText passwordEditText;
	private EditText usernameEditText;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		usernameEditText = (EditText) findViewById(R.id.usernameEditText);
		passwordEditText = (EditText) findViewById(R.id.passwordEditText);
		loginButton = (Button) findViewById(R.id.loginButton);
		loginButton.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_login, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.loginButton:
			try {
				DAXCApp.getInstance().xmppClient = Executors
						.newSingleThreadExecutor().submit(this).get();
				Intent intent = new Intent(this, HomeActivity.class);
				startActivity(intent);
			} catch (Exception e) {
				Toast.makeText(this, "Invalid username or password",
						Toast.LENGTH_LONG).show();
				e.printStackTrace();
			}
			break;
		}
	}

	@Override
	public XmppClient call() throws Exception {
		XmppClient x = new XmppClient(usernameEditText.getText().toString(),
				"gmail.com", null, passwordEditText.getText().toString());
		return x;
	}

}
